import Vue from 'vue';
import dingtalk from '@src/util/dingtalk';
import FrameView from './FrameView.vue';
import { Notification } from 'element-ui';
import mtracker from '@src/util/mtracker';
import { Loading } from 'element-ui';
import { getAsyncSystemFrameInitData } from '@src/api/InitDataApi'
import qs from 'qs';
import platform from '@src/platform';
import { getPcHomePageMenuList } from '@src/api/UserCenterApi.js';
import platformExtension from '@src/platform/extension'
import { getRootWindow } from '@src/util/dom'

import { isDevelopment } from '@src/util/platform'

window.onload = function(){
  window.Notification.requestPermission()
}
import VueTour from 'vue-tour';
import 'vue-tour/dist/vue-tour.css';
Vue.use(VueTour);

mtracker();

window.__exports__notification = Notification;
window.open_insideIM = platform.open_insideIM
const componentItem = (initData) => {
  return {
    provide: {
      initData: Object.freeze(initData)
    },
    render(h) {
      return h(FrameView);
    }
  }
}

Vue.component('async-component', function(resolve) {
  
  // 需要加loading 打开此注释
  const instance = Loading.service({ fullscreen: true });
  
  let query = qs.parse(window.location.search.substr(1));
  const params = Object.assign({}, query, {})
  
  getAsyncSystemFrameInitData(params).then( async result => {
    let initData = result?.data?.initJson || {}
    const title = (result && result.data && result.data.title) || ''
    document.title = title
    const isSuccess = result.succ || result.success
    const isProduction = process.env.NODE_ENV === 'production' || !isDevelopment();
    try {
      /** 
       * @description 如果是返回 PUB_VERSION 值 
       * 则代表当前租户的cookie上的版本号 与 当前租户实际的版本号不一致
       * 需要更新 cookie 上的版本号，并且刷新页面
      */
      if (initData?.PUB_VERSION && isProduction) {
        document.cookie = `PUB_VERSION=${initData.PUB_VERSION};path=/;`
        window.location.reload()
      }
    } catch (error) {
      console.error(error)
    }
    
    try {
      const { data } = await getPcHomePageMenuList();
      initData.barPageList = data.barPageList || [];
      initData.morePageList = data.morePageList || [];
      initData.showUploadTenantLogo = data.showUploadTenantLogo;
      initData.calendar = data.showCalendar;
      initData.notice = data.showNotice;
    } catch (error) {
      console.error('getPcHomePageMenuList 失败', error);
    }
    
    if (!isSuccess) {
      window.location.href = '/500'
      return 
    }
    
    if(window.DingTalkPC) dingtalk.sign(initData.ddConfig);

    try {
      window._init = JSON.stringify(initData)
    } catch (error) {
      console.error('initData 赋值失败')
    }
    // 企微端需要在这里签名
    if(initData.tenantType == 2) {
      const rootWindow = getRootWindow(window)
      if (rootWindow.wxConfig) {
        // platformExtension.injectAuth(rootWindow.wxConfig)
      } else {
        try {
          await platformExtension.sign()
          eventBus.$emit('wx-sign-done')
        } catch (error) {
          console.warn('wx sign', error);
        }
      }
    }

    // 需要加loading 打开此注释
    instance.close();
    
    // if (window.frameElement) {
    //   const currentTabId = window.frameElement.dataset.id;
    //   platform.setTabTitle({
    //     id: currentTabId,
    //     title
    //   })
    // }
   
    resolve(componentItem(initData))
    
  }).catch(error => {
    console.error(error)
    window.location.href = '/500'
  })
  
});

let app = {
  render(h) {
    return <async-component />
  },
}

export default app;
